package com.lwl.office.webeditor.parser;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.lwl.office.webeditor.ParserContext;
import com.lwl.office.webeditor.style.PStyle;
import com.lwl.office.webeditor.style.Style;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.jsoup.nodes.Node;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTVerticalJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;

import java.util.List;

public class CellNodeParser extends NodeParser{
    @Override
    public void parser(ParserContext context, Style style) {
        context.setRpt(ParserContext.RPT.CELL);
        //单元格创建自然段
        List<XWPFParagraph> paragraphs = context.getCell().getParagraphs();
        if(CollUtil.isNotEmpty(paragraphs)){
            context.setParagraph(paragraphs.get(0));
        }else{
            context.createParagraph();
        }
        //单元格设置样式
        Node cell = getNode();
        //1.是否首行
        String rowClass = cell.parentNode().attr("class");
        //tr的class属性包含firstRow,则表示当前是首行
        if(StrUtil.isNotEmpty(rowClass) && rowClass.contains("firstRow")){
            //TODO 首行渲染
        }
        //2.单元格文本排列方式
        //垂直方向排列
        String valign = cell.attr("valign");
        if(StrUtil.isNotEmpty(valign)){
            CTVerticalJc ctVerticalJc = context.getCell().getCTTc().addNewTcPr().addNewVAlign();
            if(valign.equals("top")){
                ctVerticalJc.setVal(STVerticalJc.TOP);
            }else if(valign.equals("bottom")){
                ctVerticalJc.setVal(STVerticalJc.BOTTOM);
            }else{
                ctVerticalJc.setVal(STVerticalJc.CENTER);
            }
        }
        //水平方向
        String align = cell.attr("align");
        if(StrUtil.isNotEmpty(align)){
            CTJc ctJc = context.getParagraph().getCTP().addNewPPr().addNewJc();
            if(align.equals("center")){
                ctJc.setVal(STJc.CENTER);
            }else if(align.equals("right")){
                ctJc.setVal(STJc.RIGHT);
            }else{
                ctJc.setVal(STJc.LEFT);
            }
        }
        PStyle pStyle = new PStyle();
        pStyle.setTextAlign(align);
        for (Node node : cell.childNodesCopy()) {
            ParserSelector.select(node).parser(context,pStyle);
        }
        context.setRpt(null);
    }
}
